//
//  Controller.cpp
//  all_test04
//
//  Created by Jarosław Wojtasik on 18.06.2013.
//  Copyright (c) 2013 Jarosław Wojtasik. All rights reserved.
//

#include "Controller.h"
#include "Graphics.h"

static const double kFrameSpeed = 1. / 30.;


Controller::Controller() {

}

Controller::~Controller() {
    
}

void Controller::setRotator( std::shared_ptr<Rotator> rotator ) {
    _rotator = rotator;
}


void Controller::start() {

    // -- create queue --
    _eventQueue =  al_create_event_queue();
    // -- register sources --
	// - mouse
    // - timer
    _frameTimer = al_create_timer( kFrameSpeed );
	ALLEGRO_EVENT_SOURCE* timerSource = al_get_timer_event_source( _frameTimer );
	al_register_event_source( _eventQueue, timerSource);

    // -- start things
    al_start_timer( _frameTimer );
    
    // -- event queue --
    ALLEGRO_EVENT event;
    bool notDone = true;
    ALLEGRO_MOUSE_STATE mouseState;
    
    while (notDone) {
        al_wait_for_event( _eventQueue, &event);

        if ( event.type == ALLEGRO_EVENT_TIMER ) {
            Graphics::getGraphics().clear();
			Graphics::getGraphics().drawCenterLines();
			// --
			al_get_mouse_state( &mouseState );
			_rotator->turnTowardPoint( mouseState.x, mouseState.y );
			_rotator->update();
			_rotator->draw();
			// --

			Graphics::getGraphics().step();
        }
    }
   
}

void Controller::stop() {
    // -- stop things --
    al_stop_timer( _frameTimer );

    // -- unregister sources --
    // - timer
    ALLEGRO_EVENT_SOURCE* timerSource = al_get_timer_event_source( _frameTimer );
    al_unregister_event_source( _eventQueue, timerSource );
    al_destroy_timer( _frameTimer );
    
    al_flush_event_queue( _eventQueue );
    al_destroy_event_queue( _eventQueue );
}